package com.ihtry.util;

import com.ihtry.dao.BookDao;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Part;
import java.io.File;
import java.util.Random;


//图片上传处理
public class FileTool {
    /**
     * 获取文件名
     *
     * @param part 文件
     * @return 文件名
     */
    public String getFileName(Part part) {
        if (part == null) {
            return null;
        }
        String header = part.getHeader("Content-Disposition");
        if (StringUtils.isAllBlank(header)) {
            return null;
        }
        return StringUtils.substringBetween(header, "filename=\"", "\"");
    }

    /**
     * 获取文件后缀
     *
     * @param fileName 文件名
     * @return java.lang.String
     */
    public String getFileExt(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return null;
        }
        return StringUtils.substringAfterLast(fileName, ".");
    }

    /**
     * 删除文件
     *
     * @param realPath 文件路径
     * @param id id
     */
    public void deleteFile(String realPath, Integer id) {
        BookDao bookDao = new BookDao();
        String sqlPath = bookDao.getFilePath(id);
        String filename = StringUtils.substringAfterLast(sqlPath, "static/upload/");
        String path = realPath + File.separator + filename;
        if (StringUtils.isBlank(path)) {
            System.out.println("文件不存在");
        }
        boolean delete = new File(path).delete();
        System.out.println("删除状态：" + delete);

    }

    //生成随机字符串
    public String getRandomString() {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        int size = base.length();
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 16; i++) {
            int number = random.nextInt(size);
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}
